//
//  SubscriptionsViewController.m
//  Feeder
//
//  Created by Diego Acosta on 7/19/10.
//  Copyright __MyCompanyName__ 2010. All rights reserved.
//

#import "SubscriptionsViewController.h"
#import "LoginViewController.h"
#import "FolderViewController.h"
#import "FeederAppDelegate.h"
#import "RequestStatusView.h"
#import "TDBadgedCell.h"
#import "GoogleReader.h"
#import "UserDefaultsHelper.h"


#define kActionSheetLogoutAction 0

#define kTableViewSectionHome 0
#define kTableViewSectionHomeCount 6
#define kTableViewSectionHomeTitle @"Home"

#define kHomeAllItemsCell 0
#define kHomeKeptUnreadCell 1
#define kHomeStarredCell 2
#define kHomeSharedCell 3
#define kHomeNotesCell 4
#define kHomeFollowCell 5

#define kTableViewSectionSubs 1
#define kTableViewSectionSubsTitle @"Subscriptions"


@interface SubscriptionsViewController(Private)

- (void)_logout;
- (void)_getAllData;
- (void)_setupToolbar;
- (NSString *)_formatUsername:(NSString *)username;

@end

@implementation SubscriptionsViewController

- (void)viewDidLoad {
	
    [super viewDidLoad];
	
	// show username as view title.
	self.navigationItem.title = [self _formatUsername:[UserDefaultsHelper username]];
	
	// show logout button.
	self.navigationItem.leftBarButtonItem = [[UIBarButtonItem alloc] initWithTitle:@"Logout"
																			  style:UIBarButtonItemStylePlain
																			 target:self
																			action:@selector(_logout)];
	// initialize local data.
	allunreads = [[NSString alloc] initWithString:@""];
	tags = [[NSDictionary alloc] init];
	folders = [[NSDictionary alloc] init];
	feeds = [[NSDictionary alloc] init];
	
	// configure toolbar.
	[self _setupToolbar];
}

- (void)didReceiveMemoryWarning {
    // Releases the view if it doesn't have a superview.
    [super didReceiveMemoryWarning];
    
    // Relinquish ownership any cached data, images, etc that aren't in use.
}

- (void)viewDidUnload {
    // Relinquish ownership of anything that can be recreated in viewDidLoad or on demand.
    // For example: self.myOutlet = nil;
}

- (void)viewDidAppear:(BOOL)animated {
	
	// get app delegate.
	FeederAppDelegate * delegate = (FeederAppDelegate *)[[UIApplication sharedApplication] delegate];
	
	if (delegate.loadAllData == YES) {
		
		// get all data.
		[self _getAllData];
		
		// go back to defaults.
		delegate.loadAllData = NO;
	}
	
	[super viewDidAppear:animated];
}


#pragma mark -
#pragma mark Private methods

- (void)_logout {

	UIActionSheet * action = [[UIActionSheet alloc] initWithTitle:nil
														 delegate:self
												cancelButtonTitle:@"Cancel"
										   destructiveButtonTitle:@"Logout"
												otherButtonTitles:nil];
	
	[action showInView:[self.view window]];
	[action release];
}

- (void)_getAllData {
	
	// get credentials.
	NSString * auth = [UserDefaultsHelper auth];
	
	// init resources.
	if (reader == nil) {
		
		reader = [[GoogleReader alloc] initWithAuth:auth];
		[reader setDelegate:self];
	}
	
	// if service status is not idle, abort operation.
	if ([reader requestStatus] != RequestActionIdle) {
		return;
	}
	
	// set request status.
	[requestStatus setRequestStatus:RequestStatusWorking];
	
	// get all data.
	[reader getAllData];
}

- (void)_setupToolbar {

	UIBarButtonItem * refresh = [[UIBarButtonItem alloc] initWithBarButtonSystemItem:UIBarButtonSystemItemRefresh
																			  target:self
																			  action:@selector(_getAllData)];
	
	
	UIBarButtonItem * config = [[UIBarButtonItem alloc] initWithImage:[UIImage imageNamed:@"gear.png"]
																style:UIBarButtonItemStylePlain
															   target:nil
															   action:nil];
	// flexible space.
	UIBarButtonItem * flexspace = [[UIBarButtonItem alloc] initWithBarButtonSystemItem:UIBarButtonSystemItemFlexibleSpace
																				target:nil
																				action:nil];
	
	// status message.
	requestStatus = [[RequestStatusView alloc] init];
	
	UIBarButtonItem * status = [[UIBarButtonItem alloc] initWithCustomView:requestStatus];
	
	NSArray * buttons = [NSArray arrayWithObjects:refresh, flexspace, status, flexspace, config, nil];
	
	// add butons into toolbar.
	[self setToolbarItems:buttons animated:YES];
}

- (NSString *)_formatUsername:(NSString *)username {

	// if user it's not using a google account the username is the entire email.
	NSArray * split = [username componentsSeparatedByString:@"@"];
	
	if ([split count] > 0) {
		
		// let's use only the username behind the at sign.
		return [split objectAtIndex:0];
	}

	// without at sign, it's google account.
	return username;
}

#pragma mark -
#pragma mark UIActionSheetDelegate methods

- (void)actionSheet:(UIActionSheet *)actionSheet clickedButtonAtIndex:(NSInteger)buttonIndex {
	
	// user wants to logout.
	if (buttonIndex == kActionSheetLogoutAction) {
		
		// clear credentials.
		[UserDefaultsHelper setAuth:nil];
		
		// delete reader object;
		[reader release]; reader = nil;
		
		// show login window.
		LoginViewController * loginController = [[LoginViewController alloc] initWithNibName:@"LoginView"
																					  bundle:nil];
		
		[self.navigationController presentModalViewController:loginController animated:YES];
		[loginController release];
	}
}

#pragma mark -
#pragma mark UITableViewDelegate methods

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {

	if (indexPath.section == kTableViewSectionHome) {
		
		return;
	}
	else if (indexPath.section == kTableViewSectionSubs) {
		
		NSArray * rootprefs = [prefs objectForKey:kStreamPrefsRootNode];
		NSString * tagid = [rootprefs objectAtIndex:indexPath.row];
		
		GRTagIdCollection collection = [reader collectionForTagId:tagid];
		
		// we've to check what user have selected.
		if (collection == GRTagIdCollectionFolder) {
			
			NSDictionary * folder = [folders objectForKey:tagid];
			NSArray * folderprefs = [prefs objectForKey:tagid];
			
			FolderViewController * fvc = [[FolderViewController alloc] initWithNibName:@"FolderView"
																				bundle:nil];
			
			// pass folder and prefs for the folder we want to show.
			fvc.folder = folder;
			fvc.folderprefs = folderprefs;
			
			[self.navigationController pushViewController:fvc animated:YES];
			[fvc release];
		}
		else if (collection = GRTagIdCollectionFeed) {
			
			// do something.
		}
		else if (collection = GRTagIdCollectionTag) {
			
			// do something.
		}
	}
}

#pragma mark -
#pragma mark UITableViewDataSource methods

// Customize the number of sections in the table view.
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {

	NSUInteger sectionsCount = 1;
	
	// check first if there's any folders or feeds.
	if ([folders count] > 0 || [feeds count] > 0) {
		
		sectionsCount++;
	}
	
	return sectionsCount;
}

// Customize the number of rows in the table view.
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
	
	if (section == kTableViewSectionHome) {
		
		return kTableViewSectionHomeCount;
	}
	else if (section == kTableViewSectionSubs) {
		
		return [folders count] + [feeds count] + [tags count];
	}
	
	return 0;
}

// Customize the appearance of table view cells.
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {

	static NSString * CellIdentifier = @"BadgedCell";
	
	TDBadgedCell * cell = (TDBadgedCell *)[tableView dequeueReusableCellWithIdentifier:CellIdentifier];
	if (cell == nil) {
		cell = [[[TDBadgedCell alloc] initWithStyle:UITableViewCellStyleDefault
									reuseIdentifier:CellIdentifier] autorelease];
		
		// cell defaults.
		cell.badgeColor = [UIColor colorWithRed:140.0 / 255
										  green:153.0 / 255
										   blue:180.0 / 255
										  alpha:1.0];
		
		cell.accessoryType = UITableViewCellAccessoryDisclosureIndicator;
	}

	// customize cell.
	cell.badgeNumber = @"";
	
	if (indexPath.section == kTableViewSectionHome) {
		
		if (indexPath.row == kHomeAllItemsCell) {
			
			cell.textLabel.text = @"All items";
			cell.badgeNumber = allunreads;
		}
		else if (indexPath.row == kHomeKeptUnreadCell) {
			cell.textLabel.text = @"Kept unread";
		}
		else if (indexPath.row == kHomeStarredCell) {
			cell.textLabel.text = @"Starred";
		}
		else if (indexPath.row == kHomeSharedCell) {
			cell.textLabel.text = @"Shared";
		}
		else if (indexPath.row == kHomeNotesCell) {
			cell.textLabel.text = @"Notes";
		}
		else if (indexPath.row == kHomeFollowCell) {
			cell.textLabel.text = @"People you follow";
		}
	}
	else if (indexPath.section == kTableViewSectionSubs) {
		
		// pull root node streamprefs.
		NSArray * rootprefs = [prefs objectForKey:kStreamPrefsRootNode];
		NSString * tagid = [rootprefs objectAtIndex:indexPath.row];
		
		// we've to check if we're on a folder, feed or a tag.
		GRTagIdCollection collection = [reader collectionForTagId:tagid];
		if (collection == GRTagIdCollectionFolder) {

			NSDictionary * folder = [folders objectForKey:tagid];
			
			cell.textLabel.text = [folder objectForKey:@"label"];
			cell.badgeNumber = [folder objectForKey:@"count"];
		}
		else if (collection == GRTagIdCollectionFeed) {
			
			NSDictionary * sub = [feeds objectForKey:tagid];
			
			cell.textLabel.text = [sub objectForKey:@"title"];
			cell.badgeNumber = [sub objectForKey:@"count"];
		}
		else if (collection == GRTagIdCollectionTag) {
			
			NSDictionary * tag = [tags objectForKey:tagid];
			
			cell.textLabel.text = [tag objectForKey:@"label"];
		}
	}
	
	return (UITableViewCell *)cell;
}

- (NSString *)tableView:(UITableView *)tableView titleForHeaderInSection:(NSInteger)section {
	
	if (section == kTableViewSectionHome) {
		
		return kTableViewSectionHomeTitle;
	}
	else if (section == kTableViewSectionSubs) {
		
		return kTableViewSectionSubsTitle;
	}
	
	return @"";
}

#pragma mark -
#pragma mark GoogleReaderDelegate methods

- (void)requestFinished {
	
	// we've finished.
	[requestStatus setRequestStatus:RequestStatusUpdated];
	
	// copy reader data into local objects.
	allunreads = [reader.allunreads copy];
	tags = [reader.tags copy];
	folders = [reader.folders copy];
	feeds = [reader.feeds copy];
	prefs = [reader.prefs copy];
	
	// reload data.
	[self.tableView reloadData];
}

- (void)requestWillStartWithAction:(RequestAction)action {

	NSString * message = @"";
	
	if (action == RequestActionGetTags) {
		
		message = @"Loading tags...";
	}
	else if (action == RequestActionGetSubs) {
		
		message = @"Loading subscriptions...";
	}
	else if (action == RequestActionGetStreamPrefs) {
		
		message = @"Loading preferences...";
	}
	else if (action == RequestActionUnreadCount) {
		
		message = @"Counting unreads...";
	}
	
	// update message.
	[requestStatus setMessageForWorkingStatus:message];
}

#pragma mark -

- (void)dealloc {

	[reader release];
	[requestStatus release];
	[tags release];
	[folders release];
	[feeds release];
	[prefs release];
    [super dealloc];
}

@end